<template>
  <!--      地图部分-->
  <div class="map-container">
    <div class="map-title">监测点分布</div>

    <div class="map-controls">
      <input
          type="text"
          placeholder="搜索设备点..."
          v-model="searchTerm"
          @input="filterDevices"
          class="search-input"
      >
      <div class="map-legend">
        <div class="legend-item">
          <div class="legend-color active"></div>
          <span>运行中</span>
        </div>
        <div class="legend-item">
          <div class="legend-color inactive"></div>
          <span>离线</span>
        </div>
      </div>
    </div>
    <div class="map-drive" ref="mapContainer"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref,reactive, onMounted, onUnmounted, computed } from 'vue'
//忽略错误
//@ts-ignore
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll'
import AMapLoader from '@amap/amap-jsapi-loader'

// 导入设备图标
import activeDeviceIcon from '@/assets/map/1.png'
import inactiveDeviceIcon from '@/assets/map/2.png'

// 图标映射
const deviceIcons = {
  active: activeDeviceIcon,
  inactive: inactiveDeviceIcon
}

// 创建地图容器引用
const mapContainer = ref<HTMLElement | null>(null)
let map: any = null
let AMap: any = null
const searchTerm = ref('')

// 设备点类型定义
interface DevicePoint {
  id: number
  name: string
  lat: number
  lng: number
  status: 'active' | 'inactive'
}

// 设备点数据
const devicePoints = ref<DevicePoint[]>([
  { id: 1, name: '湿地公园监测点', lat: 39.9042, lng: 116.4074, status: 'active' },
  { id: 2, name: '森林保护区监测点', lat: 39.9142, lng: 116.4274, status: 'active' },
  { id: 3, name: '湖泊观测站', lat: 39.8942, lng: 116.3974, status: 'inactive' },
  { id: 4, name: '山区监测站', lat: 39.9242, lng: 116.4474, status: 'active' },
  { id: 5, name: '城市生态园', lat: 39.8842, lng: 116.3874, status: 'active' },
  { id: 6, name: '鸟类保护区东站', lat: 39.8992, lng: 116.4174, status: 'active' },
  { id: 7, name: '湿地西观测点', lat: 39.9092, lng: 116.3924, status: 'inactive' },
  { id: 8, name: '森林北监测点', lat: 39.9192, lng: 116.4424, status: 'active' }
])

// 当前显示的设备点
const currentMarkers = ref<any[]>([])

const createMarkerContent = (point: DevicePoint) => {
  const iconUrl = deviceIcons[point.status]
  const color = point.status === 'active' ? '#4361ee' : '#ef4444'

  return `
    <div style="
      position: relative;
      width: 48px;
      height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s ease;
      z-index: 10;
      ${point.status === 'active' ? 'animation: pulse 2s infinite;' : ''}
    ">


      <!-- 设备图标 -->
      <img src="${iconUrl}" alt="设备图标" style="
        width: 35px;
        height: 35px;
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
        z-index: 11;
      ">

      <!-- 设备名称提示 -->
      <div style="
        position: absolute;
        top: -40px;
        left: 50%;
        transform: translateX(-50%);
        background: white;
        padding: 6px 12px;
        border-radius: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        white-space: nowrap;
        display: none;
        font-size: 12px;
        font-weight: 600;
        color: #2c3e50;
        z-index: 20;
      ">${point.name}</div>
    </div>
  `
}

// 添加设备点标记到地图
const addDeviceMarkers = (devices: DevicePoint[]) => {
  if (!map || !AMap) return

  // 清除现有标记
  currentMarkers.value.forEach(marker => map.remove(marker))
  currentMarkers.value = []

  // 添加新标记
  devices.forEach(point => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(point.lng, point.lat),
      content: createMarkerContent(point),
      offset: new AMap.Pixel(-24, -24), // 调整为图标中心
      zIndex: 10,
    })

    map.add(marker)
    currentMarkers.value.push(marker)

    // 添加点击事件
    marker.on('click', () => {
      // 创建信息窗口
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div class="map-popup">
            <h3>${point.name}</h3>
            <p>状态: <span class="${point.status === 'active' ? 'active-status' : 'inactive-status'}">${point.status === 'active' ? '运行中' : '离线'}</span></p>
            <p>设备ID: ${point.id}</p>
            <p>坐标: ${point.lat.toFixed(4)}, ${point.lng.toFixed(4)}</p>
            <button class="map-btn" onclick="alert('查看设备 ${point.id} 详情')">查看详情</button>
          </div>
        `,
        offset: new AMap.Pixel(0, -30),
        autoMove: true,
        closeWhenClickMap: true,
      })

      // 打开信息窗口
      infoWindow.open(map, [point.lng, point.lat])
    })

    // 添加鼠标悬浮事件
    marker.on('mouseover', () => {
      const contentElement = marker.getContent()
      if (contentElement && contentElement.querySelector) {
        const tooltip = contentElement.querySelector('div:nth-child(2)')
        if (tooltip) tooltip.style.display = 'block'
      }
    })

    marker.on('mouseout', () => {
      const contentElement = marker.getContent()
      if (contentElement && contentElement.querySelector) {
        const tooltip = contentElement.querySelector('div:nth-child(2)')
        if (tooltip) tooltip.style.display = 'none'
      }
    })
  })
}

// 过滤设备点
const filterDevices = () => {
  const filtered = searchTerm.value
      ? devicePoints.value.filter(d =>
          d.name.toLowerCase().includes(searchTerm.value.toLowerCase())
      )
      : [...devicePoints.value]

  addDeviceMarkers(filtered)
}

// 初始化地图
async function initMap(){
  try {
    AMap = await AMapLoader.load({
      key: 'e23d3a8e7bc54ba97e2d85b5541257f3', // 替换为您的Key
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType', 'AMap.Geolocation']
    })

    if (mapContainer.value) {
      // 创建地图实例
      map = new AMap.Map(mapContainer.value, {
        center: [116.4074, 39.9042], // [经度, 纬度]
        zoom: 12,
        viewMode: '3D',
        mapStyle: 'amap://styles/light',
      })

      // 添加控件
      map.addControl(new AMap.ToolBar())
      map.addControl(new AMap.Scale())
      map.addControl(new AMap.MapType({
        showRoad: true,
        showTraffic: false
      }))

      // 初始添加所有设备点
      filterDevices()
    }
  } catch (error) {
    console.error('高德地图加载失败:', error)
  }
}

// 挂载地图
onMounted(
    () => {

      initMap()
    }
)

// 销毁地图实例
onUnmounted(() => {
  if (map) {
    map.destroy()
    map = null
  }
})


</script>

<style scoped>
.map-container {
  height: 85%;
  width: 65%;
  padding: 0 2% 2% 2%;
  background: linear-gradient(145deg, #f0f3f8, #e5e9f0); /* 双色渐变背景 */
  border-radius: 12px; /* 增加圆角 */
  box-shadow:
      0 6px 18px rgba(0, 0, 0, 0.1),
      0 0 0 1px rgba(0, 0, 0, 0.05); /* 复合阴影 + 描边效果 */
  border: 1px solid #d5dae0; /* 添加精细边框 */
}

.map-title {
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  height: 60px;
  line-height: 60px;
  border-bottom: 3px solid #e9ecef;
  margin-bottom: 15px;

}

.map-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-input {
  padding: 10px 15px;
  border: 1px solid #ced4da;
  border-radius: 5px;
  width: 70%;
  font-size: 16px;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.25);
}

.map-legend {
  display: flex;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 0 5px rgba(0,0,0,0.2);
}

.legend-color.active {
  background: #4361ee;
}

.legend-color.inactive {
  background: #ef4444;
}

.map-drive {
  height: calc(100% - 110px); /* 减去标题和控件高度 */
  width: 100%;
  border-radius: 10px;
  overflow: hidden;
  background: #e9ecef;
}

/* 高德地图弹出框样式 */
:deep(.map-popup) {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  padding: 10px;
  min-width: 250px;
}

:deep(.map-popup h3) {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 16px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 5px;
}

:deep(.map-popup p) {
  margin: 5px 0;
  font-size: 14px;
  color: #495057;
}

:deep(.active-status) {
  color: #10b981;
  font-weight: bold;
}

:deep(.inactive-status) {
  color: #ef4444;
  font-weight: bold;
}

:deep(.map-btn) {
  background: #4361ee;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  margin-top: 10px;
  width: 100%;
  transition: all 0.3s ease;
}

:deep(.map-btn:hover) {
  background: #3a0ca3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}



</style>